/*
 * Created on 22.11.2004
 */
package servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BookDao;
import dao.BookDaoImpl;
import dao.DaoFactory;
import exception.BookNotDeletedException;
import exception.BookNotFoundException;
import exception.BookNotSavedException;

import model.Book;

public class BookEdit extends HttpServlet {	
	
	private static final long serialVersionUID = 1L;
	
	final BookDao bookDao = DaoFactory.getInstance().getBookDao();

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		String action = request.getParameter("action");
		
		if (action == null) {
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/error.jsp");
			dispatcher.forward(request, response);
		}
				
		Long id = null;
		
		if (request.getParameter("id") != null) {
			id = Long.valueOf(request.getParameter("id"));
		}
				
		if(action.equals("add")){
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/add.jsp");
			dispatcher.forward(request, response);		
		} else if(action.equals("edit")) {			
			try {
				Book book = bookDao.get(id);
				request.setAttribute("book", book);
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/edit.jsp");
				dispatcher.forward(request, response);
			} catch (BookNotFoundException e) {
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/error.jsp");
				dispatcher.forward(request, response);
			}				
		} else if(action.equals("delete")) {			
			try {
				bookDao.delete(id);
				response.sendRedirect(request.getContextPath() + "/list");
			} catch (BookNotDeletedException e) {
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/error.jsp");
				dispatcher.forward(request, response);
			}
		}		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		
		Long id = null;
		
		if(request.getParameter("id") != null) {
			id = Long.valueOf(request.getParameter("id"));
		}
		
		String author = request.getParameter("author");
		String title = request.getParameter("title");
				
		Book book = new Book();		
		book.setId(id);
		book.setTitle(title);
		book.setAuthor(author);		
		
		try {		
			bookDao.save(book);
			response.sendRedirect(request.getContextPath() + "/list");
		}  catch (BookNotSavedException e) {
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/error.jsp");
			dispatcher.forward(request, response);
		}
	}
}
